import {_decorator, Component, tween, Vec3} from 'cc';
import {GameManager} from "db://assets/scripts/game/GameManager";
import {PoolManager} from "db://assets/scripts/common/PoolManager";
import {MonsterController} from "db://assets/scripts/game/role/monster/MonsterController";

const {ccclass, property} = _decorator;

/**
 * 圆圈预警脚本
 */
@ccclass('WarningCircleEffect')
export class WarningCircleEffect extends Component {
    /**
     * 循环缩小放大tween实例
     */
    private tweenLoop: any;
    /**
     * 缩小消失tween实例
     */
    private tweenHide: any;
    /**
     * 目标的世界坐标
     */
    private targetWorldPosition: Vec3 = new Vec3();
    /**
     * 缩放1
     */
    private targetScale1: Vec3 = new Vec3();
    /**
     * 缩放2
     */
    private targetScale2: Vec3 = new Vec3();
    /**
     * 缩放3
     */
    private targetScale3: Vec3 = new Vec3();
    /**
     * 父脚本
     */
    private parentScript: MonsterController;

    /**
     * 初始化圆圈预警脚本
     *
     * @param scale 缩放比
     * @param parentScript 父脚本
     */
    public init(scale: number, parentScript: MonsterController) {
        parentScript.recycleWarning();
        this.parentScript = parentScript;
        this.targetScale1.set(scale, scale, scale);
        this.targetScale2.set(scale * 0.8, scale * 0.8, scale * 0.8);
        this.node.setScale(this.targetScale3);

        let playerWorPos = GameManager.getInstance().gamePlayerProxy.getPlayerNode().worldPosition;
        this.targetWorldPosition.set(playerWorPos.x, playerWorPos.y + 0.2, playerWorPos.z);
        this.node.setWorldPosition(this.targetWorldPosition);

        this.closeTween();
        this.showWarning();
    }

    /**
     * 显示预警
     */
    public showWarning() {
        let showTime = 0.4;

        this.tweenLoop = tween(this.node)
            .to(showTime, {scale: this.targetScale1}, {easing: "smooth"})
            .start();
    }

    /**
     * 隐藏预警
     */
    public hideWarning() {
        this.closeTween();

        this.tweenHide = tween(this.node)
            .to(0.3, {scale: this.targetScale3}, {easing: "backInOut"})
            .call(() => {
                PoolManager.getInstance().putNode(this.node);
                this.closeTween();
            })
            .start();
    }

    /**
     * 关闭缓动
     */
    private closeTween() {
        if (this.tweenHide) {
            this.tweenHide.stop();
            this.tweenHide = null;
        }

        if (this.tweenLoop) {
            this.tweenLoop.stop();
            this.tweenLoop = null;
        }
    }
}